<?php

namespace common\model\sell66;

use common\db\Sell66;
use common\libs\ExchangeRate;
use think\Cache;

class SteamItem extends Sell66
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'steam_item';
    protected $pk = 'item_id';

    public static $statusMaps = [
    		'active'=>['in', [1]],
    		'disabled'=>2
    ];

    public static function getItemInfoByHashName($appId,$hashName){
        $itemInfo = static::where([
            'market_hash_name' => $hashName,
			'app_id'=>$appId,
        	'iteam_status'=>self::$statusMaps['active']
        ])->order(['second'=>'desc'])->find();
        if (empty ($itemInfo)) {
            return [];
        }
        $itemInfo->iteam_status = 1;
        return $itemInfo;
    }

    /**
     * 根据价格数组修改Iteam价格
     * @param array $priceInfo
     */
    public static function updateSteamIteamPriceInsert($priceInfo = [])
    {
        self::update(['status' => 2], ['status' => 1]);

        $tmp_list = [];
        foreach ($priceInfo as $key => $value) {
            $tmp_data = [];
            $tmp_data['market_hash_name'] = $key;
            $tmp_data['source_price'] = $value['safe_price'] ? $value['safe_price'] : 0;
//            $tmp_data['price'] = $tmp_data['steam_price'] ? $tmp_data['steam_price'] * 6.89 : 0;
            $tmp_list[] = $tmp_data;
        }

        // $tmp_list_count = count($tmp_list);

        $tmp_list_chunk = array_chunk($tmp_list, 10);
        foreach ($tmp_list_chunk as $val) {
            self::insertAll($val);
        }
    }

    /**
     **
     * 根据价格数组修改Iteam价格
     * @param array $priceInfo
     */
    public static function updateSteamIteamPrice($priceInfo = [])
    {
        foreach ($priceInfo as $key => $value) {
            $tmp_data = [];
            $tmp_data['steam_price'] = $value['safe_price'] ? $value['safe_price'] : 0;
            $tmp_data['price'] = $tmp_data['steam_price'] ? $tmp_data['steam_price'] * 6.89 : 0;

            $where['market_hash_name'] = $key;
            self::update($tmp_data, $where);
        }
    }

    /**
     * 通过Analyst获取价格
     * @param array $priceInfo
     * @return array
     */
    public static function updateCsgoPriceByAnalyst($priceInfo = [])
    {
        //获取汇率
        $appId = 730;
        $steamItem = new SteamItem();
        $steamPriceLog = new SteamPriceLog();
        $rate = ExchangeRate::getRate();
        $rate = $rate ? $rate : 6.89;
        $second = date('ymd');

        $connection = ($steamItem)->db();
        $connection->startTrans();
        try {
            //拼装并添加数据
            $time = time();
            foreach ($priceInfo as $key => $value) {
                echo $key . PHP_EOL;
                //查询商品当前价格
                $itemInfo = $steamItem->where('market_hash_name', '=', $value['market_name'])->where('app_id', '=', $appId)->find();

                //计算steam价格
                $steamPrice12 = $steamPriceLog->where('market_hash_name', '=', $value['market_name'])->where('second', '=', date("ymd", strtotime("-1 day")) . '1')->find();
                $steamPrice2 = $steamPriceLog->where('market_hash_name', '=', $value['market_name'])->where('second', '=', date('ymd') . '0')->find();
                if (!empty($steamPrice12) && $steamPrice12['lowest_price'] > 0) {
                    if (!empty($steamPrice2) && $steamPrice2['lowest_price'] > 0) {
                        $steamPrice = ($steamPrice12['lowest_price'] + $steamPrice2['lowest_price']) / 2;
                    } else {
                        $steamPrice = $steamPrice12['lowest_price'];
                    }
                } else {
                    if (!empty($steamPrice2) && $steamPrice2['lowest_price'] > 0) {
                        $steamPrice = $steamPrice2['lowest_price'];
                    } else {
                        $steamPrice = 0;
                    }
                }

                $addData = [];
                if (empty($itemInfo) || (!empty($itemInfo) && !in_array($itemInfo['normal'], [6, 7]) && !in_array($itemInfo['item_type'], [2]))) {

                    if (isset($value['avg_price_7_days']) && isset($value['current_price'])) {
                        $addData['source_price'] = min(sprintf("%.2f", str_replace(',', '', $value['current_price'])), sprintf("%.2f", str_replace(',', '', $value['avg_price_7_days'])));
                    } elseif (isset($value['suggested_amount_min']) && isset($value['current_price'])) {
                        $addData['source_price'] = min(sprintf("%.2f", str_replace(',', '', $value['current_price'])), sprintf("%.2f", str_replace(',', '', $value['suggested_amount_min'])));
                    } else {
                        $addData['source_price'] = 0;
                    }

                    $price = $addData['source_price'] * $rate;
                    if ($price <= 0.28 && $price > 0.21) {
                        $price = 0.04;
                    }
                    if ($price <= 0.21) {
                        $price = 0.03;
                    }

                    $addData['incoming_price'] = $price;
                    $addData['price'] = $addData['incoming_price'] * ($itemInfo['step1_ratio'] / 100);

                    if ($value['ongoing_price_manipulation'] != 0 || $addData['price'] <= 0) {
                        $addData['iteam_status'] = 2;
                        $addData['normal'] = 2;
                    } else {
                        $addData['iteam_status'] = 1;
                        $addData['normal'] = 1;
                    }
                    $addData['second'] = $second;
                    $addData['note'] = isset($itemInfo['price']) ? $itemInfo['price'] : 0;

                    SteamItemLog::create(['market_hash_name' => $value['market_name'],
                        'second' => $second,
                        'app_id' =>$appId,
                        'source' => 2,
                        'cny_price' => $addData['price'],
                        'created_time' => $time,
                        'updated_time' => $time]);
                }
                $addData['lowest_price'] = $steamPrice;
                $addData['median_price'] = isset($steamPrice2['median_price']) ? $steamPrice2['median_price'] : 0;
                $addData['volume'] = isset($steamPrice2['volume']) ? $steamPrice2['volume'] : 0;
                $addData['updated_time'] = $time;
                if (empty($itemInfo)) {
                    $addData['market_hash_name'] = $value['market_name'];
                    $addData['frist_create_time'] = $time;
                    $addData['created_time'] = $time;
                    $addData['app_id'] = $appId;

                    if (!$steamItem->insert($addData)) {
                        $connection->rollback();
                        $res = ['code' => 0, 'data' => '', 'msg' => 'steamItem中添加' . $value['market_name'] . '失败'];
                        return $res;
                    }
                } else {
                    if (!$steamItem->where(['market_hash_name' => $value['market_name'], 'app_id' => $appId])->update($addData)) {
                        $connection->rollback();
                        $res = ['code' => 0, 'data' => '', 'msg' => 'steamItem中修改' . $value['market_name'] . '失败'];
                        return $res;
                    }
                }
            }

            //销毁数组
            unset($priceInfo);

        } catch (\Exception $e) {
            $connection->rollback();
            $res = ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
            return $res;
        }

        $connection->commit();
        $res = ['code' => 1, 'data' => '', 'msg' => '成功 '];
        return $res;
    }

    /**
     * 获取物品价格列表
     * @param int $appId
     * @param int $page
     * @param int $limit
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getItemInfolist($appId = 730, $page = 1, $limit = 100){

        $count = static::where(['app_id'=>$appId,])->order(['item_id'=>'asc'])->count();
        $totalPage = ceil($count / $limit);

        $list = static::where(['app_id'=>$appId,])->field('market_hash_name, lowest_price as steam_price, price, buy_price')->limit(($page -1) * $limit, $limit)->order(['item_id'=>'asc'])->select();

        $result['count'] = $count;
        $result['totalPage'] = $totalPage;
        $result['limit'] = $limit;
        $result['currentPage'] = $page;
        $result['prevPage'] = $totalPage > 0 && $page > 1 && $page <= $totalPage ? $page - 1 : 1;
        $result['nextPage'] = $page >= $totalPage ? ($totalPage > 0 ? $totalPage : 1) : $page + 1;
        $result['list'] = $list;
        return $result;
    }


    /**
     * 根据 market_hash_name 获取物品价格信息
     * @param $marketHashName
     * @param int $appId
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getItemInfoByMarketHashName($marketHashName, $appId = 730)
    {

        $info = static::where([
            'app_id' => $appId,
            'market_hash_name' => $marketHashName,
        ])->field('market_hash_name, lowest_price as steam_price, price, buy_price')->find();

        return $info;
    }
}